package com.mjk.common.core.drpc.filter;

import com.mjk.common.util.MDCUtils;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.springframework.util.CollectionUtils;
/**
 * 基于Java的spi 机制
 * 改拦截器用于日志日志跟踪
 * @author mjk
 *	
 *order 值应该大于 RpcContext 初始化的时间
 */
@Activate(group = {CommonConstants.PROVIDER,CommonConstants.CONSUMER}, order = -1000)
public class DubboFilter implements Filter{

	@Override
	public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
		RpcContext context = RpcContext.getContext();		
		if(isConsumerSide(context)){
			MDCUtils.putMDC(context);
		}else {
			MDCUtils.getMDC(context);
		}	
		return invoker.invoke(invocation);
	}

	
	public boolean isConsumerSide(RpcContext context){
		URL url= context.getUrl();
		if(null == url){
			if(CollectionUtils.isEmpty(context.getUrls())){
				return false;
			}
			url = context.getUrls().get(0);
		}
		return url.getParameter(CommonConstants.SIDE_KEY, CommonConstants.PROVIDER_SIDE).equals(CommonConstants.CONSUMER_SIDE);
	}
}
